﻿using System;
using System.Collections.Generic;
using System.Linq;
using MiniWeb.Core.Dtos;
using MiniWeb.Core.Entities;
using MiniWeb.Core.Entities;
using WFramework.MvcPager;
using WFramework.ORM;

namespace MiniWeb.Dao
{
    public class OrdersDao : BaseDao<Orders>
    {
        public PagedList<Orders> GetPagedList(string account, string code, int? paytype, int? orderstate, DateTime? starttime, DateTime? endtime, int pageIndex, int pageSize)
        {
            var sql = Sql.Builder.Where("1=1");
            if(!string.IsNullOrEmpty(account))
            {
                sql.Where("Account =@0", account);
            }
            if(!string.IsNullOrEmpty(code))
            {
                sql.Where("Code = @0", account);
            }
            if(paytype!=null)
            {
                sql.Where("PayType =@0", paytype);
            }
            if(orderstate!=null)
            {
                sql.Where("State =@0", orderstate);
            }
            if(starttime!=null)
            {
                sql.Where("CreateDate >@0", starttime);
            }
            if(endtime !=null)
            {
                sql.Where("CreateDate < @0", endtime);
            }
            sql.OrderBy("CreateDate DESC");
            return PagedList<Orders>(pageIndex, pageSize, sql);
        }

        public Orders GetById(int id)
        {
            var sql = Sql.Builder.Where("ID = @0", id);
            return FirstOrDefault(sql);
        }

        public Orders GetByCode(string code)
        {
            var sql = Sql.Builder.Where("Code = @0", code);
            return FirstOrDefault(sql);
        }

        public void Delete(int code)
        {
            var sql = Sql.Builder.Where("Code = @0", code);
            Delete(sql);
        }


        public bool Exists(int code)
        {
            var sql = Sql.Builder.Where("Code = @0", code);
            if (FirstOrDefault(sql) != null)
            {
                return true;
            }
            return false;
        }

        public List<Orders> GetAll(int? top, string strwhere, string orderby)
        {
            string sqltop = "";
            if (top != null)
            {
                sqltop = "TOP " + top.ToString() + " * ";
            }
            else
            {
                sqltop = " * ";
            }
            var sql = Sql.Builder.Select(sqltop).From(" Orders WITH(NOLOCK)");
            if (!string.IsNullOrEmpty(strwhere))
            {
                sql.Where(strwhere);
            }
            if (!string.IsNullOrEmpty(orderby))
            {
                sql.OrderBy(orderby);
            }
            else
            {
                sql.OrderBy("CreateDate Desc");
            }

            return Query<Orders>(sql).ToList();
        }



    }
}